﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using System.Data;
public partial class administrator_uc_admin_e_products : WebPageSecurity
{
    public static string lstOtherImage = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        AjaxPro.Utility.RegisterTypeForAjax(typeof(administrator_uc_admin_e_products));
        if (!IsPostBack)
        {            
            CommonBLL.RegisterCKFinder(CKEditorBody);            
            txtNewPrice.Text = "0";
            txtOldPrice.Text = "0";
            if (!string.IsNullOrEmpty(Request.QueryString["itemid"]))
            {
                LoadDataToDropDownListCategory(DropdownParentID, 0);
                //LoadDataToDropDownListBrands(DropDownBrands);
                LoadDataInfo(Request.QueryString["itemid"].ToString().Trim());
            }            
        }
    }
    public void LoadDataInfo(string ItemID)
    {
        DataTable dt = new BLL.CmsBLL().Products_ViewItemByID(ItemID);
        if (dt.Rows.Count > 0)
        {
            txtProductID.Text = dt.Rows[0]["ProductID"] + "";
            hdItemID.Value = dt.Rows[0]["ProductID"] + "";
            lstOtherImage = dt.Rows[0]["OtherImage"] + "";
            DropdownParentID.SelectedValue = dt.Rows[0]["CateID"] + "";        
            //LoadImage(dt.Rows[0]["Image"].ToString());
            txtProductName.Text = dt.Rows[0]["ProductName"] + "";
            txtDescription.Text = dt.Rows[0]["Description"] + "";
            //CKEditorDescription.Text = "";
            CKEditorBody.Text = dt.Rows[0]["Body"] + "";
            rdActive.SelectedValue = dt.Rows[0]["Active"] + "";
           // DropDownBrands.SelectedValue = int.Parse("0"+dt.Rows[0]["BrandID"]).ToString() + "";
            txtNewPrice.Text = dt.Rows[0]["NewPrice"] + "";
            txtOldPrice.Text = dt.Rows[0]["OldPrice"] + "";
            //txtCountView.Text = dt.Rows[0]["CountView"] + "";
            //txtBaoHanh.Text = dt.Rows[0]["BaoHanh"] + "";
            txtKhuyenMaiInfo.Text = dt.Rows[0]["KhuyenMai"] + "";
            chkSPKhuyenMai.Checked = dt.Rows[0]["SPKhuyenMai"] != null?(bool)dt.Rows[0]["SPKhuyenMai"]: false;
            chkSPBanChay.Checked = dt.Rows[0]["SPBanChay"] != null ? (bool)dt.Rows[0]["SPBanChay"] : false;
            chkStatus.Checked = dt.Rows[0]["Status"]!=null?(bool)dt.Rows[0]["Status"]:false;
            chkIsNew.Checked = dt.Rows[0]["IsNew"] != null ? (bool)dt.Rows[0]["IsNew"] : false;

            if (dt.Rows[0]["OtherImage"] != null)
                LoadGridViewImage(dt.Rows[0]["OtherImage"].ToString());         
            if (dt.Rows[0]["Image"] != null)
                LoadImage(dt.Rows[0]["Image"].ToString());
        }
        else
            lblMessage.Text = "Load data failt!";
    }
    private void LoadImage(string FileName)
    {
        try
        {
            ltViewImage.Text = "<img src=\"../smallimages/" + FileName + "\" style=\"max-height:120px;\" />\n";
        }
        catch (Exception ex)
        {
            ltViewImage.Text = "Load image error! " + ex.Message;
        }
    }
    class ClsImage
    {
        public string ImageName { get; set; }
    }
    
    private void LoadGridViewImage(string OtherImage)
    {
        StringBuilder Html = new StringBuilder();
        Html.Append(
            "<div class=\"divhidden\">\n" +
            "    <input id=\"strListOtherImage\" type=\"hidden\" value=\""+OtherImage+"\" />\n" +
            "</div>\n" +
            "<table style=\"width: 200px;\" cellpadding=\"0px\" cellspacing=\"0px\">\n" +
            "	<tr>\n" +
            "		<td>\n" +
            "			Hiển thị ảnh liên quan \n" +
            "		</td>\n" +
            "		<td style=\"text-align:center; width:40px\">\n" +
            "		</td>\n" +
            "	</tr>\n");
        string[] arrListImage = OtherImage.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
        if (arrListImage.Length > 0)
        {
            for (int i = 0; i < arrListImage.Length; i++)
            {
                Html.Append(
            "	<tr>\n" +
            "		<td>\n" +
            "           <a rel=\"lightbox-journey\" title=\"" + arrListImage[i] + "\"  href=\"../images/" + arrListImage[i] + "\">\n" +
            "	            <img  style=\"height:40px;\" src=\"../smallimages/" + arrListImage[i] + "\" />\n" +
            "           </a>\n" +         
            "		</td>\n" +
            "		<td style=\"text-align:center; height:50px\">\n" +
            "			<a href=\"javascript:DeleteImageFromList('"+arrListImage[i]+"');\" title=\"Xóa\"><img src=\"../images/icons/icon_delete.jpg\" border=\"0px\"/></a> \n" +
            "		</td>\n" +
            "	</tr>\n");
            }
        }        
        Html.Append(
        "</table>\n"
        );
        ltListImages.Text = Html.ToString();
        
        //List<ClsImage> myList = new List<ClsImage>();
        //for (int i = 0; i < arrListImage.Length; i++)
        //{
        //    ClsImage item=new ClsImage();
        //    item.ImageName=arrListImage[i];
        //    myList.Add(item);
        //}
        //gv_ManageControl.DataSource = myList;
        //gv_ManageControl.DataBind();
    }
    private void LoadDataToDropDownListCategory(DropDownList cboName, int CateID)
    {
        ListItem list = new ListItem();
        cboName.Items.Clear();
        cboName.Items.Add(list);
        list.Selected = true;
        list.Value = "0";
        list.Text = "---Chọn nhóm sản phẩm---";
        DataTable dtb = new CmsBLL().Category_GetTree(CateID);
        if (dtb.Rows.Count > 0)
        {
            new CommonBLL().LoadDropDonwList(cboName, dtb, "_Title", "CateID");
        }
    }
    private void LoadDataToDropDownListBrands(DropDownList cboName)
    {
        ListItem list = new ListItem();
        cboName.Items.Clear();
        cboName.Items.Add(list);
        list.Selected = true;
        list.Value = "0";
        list.Text = "---Không chọn---";
        DataTable dtb = new CmsBLL().Brands_GetList("","");
        if (dtb.Rows.Count > 0)
        {
            new CommonBLL().LoadDropDonwList(cboName, dtb, "BrandName", "BrandID");
        }
    }
    protected void lbtEditItem_Click(object sender, EventArgs e)
    {
        if (CheckRequiteValue().Length > 0)
        {
            lblMessage.Text = CheckRequiteValue();
            return;
        }       
        lblMessage.Text = "";        
        if (FileUploadImageDaiDien.HasFile)
        {
            try
            {
                string Image = string.Empty;
                string GetValue = CommonBLL.UploadMultiImageToServer(FileUploadImageDaiDien, true, true);
                if (!string.IsNullOrEmpty(GetValue))
                {
                    if (GetValue.IndexOf("ERROR") == -1)
                        Image = GetValue;
                }
                UploadImageRelated(ref lstOtherImage);

                new CmsBLL().Products_UpDateItem(txtProductID.Text, int.Parse("0" + DropdownParentID.SelectedValue), 0 , txtProductName.Text,
                    txtDescription.Text, CKEditorBody.Text, Image, lstOtherImage, float.Parse("0" + txtOldPrice.Text), float.Parse("0" + txtNewPrice.Text), DateTime.Now,chkIsNew.Checked,
                    "", txtKhuyenMaiInfo.Text, chkSPKhuyenMai.Checked, chkSPBanChay.Checked, chkStatus.Checked, int.Parse("0" + rdActive.SelectedValue)); 
                lblMessage.Text = "Cập nhật thành công!";
                LoadDataInfo(hdItemID.Value);
                
            }
            catch (Exception ex)
            {
                lblMessage.Text = "ERROR! " + ex.Message.ToString();
            }
        }
        else
        {
            try
            {               
                UploadImageRelated(ref lstOtherImage);
                new CmsBLL().Products_UpDateItem(txtProductID.Text, int.Parse("0" + DropdownParentID.SelectedValue), 0, txtProductName.Text,
                    txtDescription.Text, CKEditorBody.Text, "", lstOtherImage, float.Parse("0" + txtOldPrice.Text), float.Parse("0" + txtNewPrice.Text), DateTime.Now, chkIsNew.Checked,
                    "", txtKhuyenMaiInfo.Text, chkSPKhuyenMai.Checked, chkSPBanChay.Checked, chkStatus.Checked, int.Parse("0" + rdActive.SelectedValue));
                lblMessage.Text = "Cập nhật thành công!";
                LoadDataInfo(hdItemID.Value);
            }
            catch (Exception ex)
            {
                lblMessage.Text = "ERROR! " + ex.Message.ToString();
            }
        }
    }
    private string CheckRequiteValue()
    {
        string RetValue = string.Empty;
        if (txtProductID.Text.Length < 3)
            RetValue += "Mã sản phẩm >=3 kí tự |";
        if (txtProductID.Text.Contains("/"))
            RetValue += "Mã sản phẩm không được chứa kí tự '/' |";
        if (txtProductName.Text == "")
            RetValue += " | Chưa nhập tên sản phẩm |";
        if (DropdownParentID.SelectedValue == "0")
            RetValue += " | Chưa chọn nhóm sản phẩm";
        return RetValue;
    }
    private void UploadImageRelated(ref string strImageRelated)
    {
        try
        {
            // Get the HttpFileCollection
            //HttpFileCollection hfc = Request.Files;
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0 && hfc.AllKeys[i].Contains("FileUploadImageRelated"))
                {
                    string FileName = hpf.FileName.Substring(hpf.FileName.LastIndexOf("\\") + 1);
                    string strFileName = CommonBLL.GetFilename(FileName);
                    hpf.SaveAs(Server.MapPath("" + DAL.EnvInfo.PathUpload + "images/") + "\\" +
                      System.IO.Path.GetFileName(strFileName));
                    CommonBLL.UploadImageToSmallImage(strFileName, hpf.InputStream, 170, 160);
                    if (string.IsNullOrEmpty(strImageRelated))
                        strImageRelated += strFileName;
                    else
                        strImageRelated += ";" + strFileName;
                }
            }
        }
        catch (Exception)
        {

        }     
    }
    //tam.jpg;anh2.mpg;anh3.bmp;anh4.gif
    [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
    public string DeleteImageFromListImage(string imagename, string strlistotherimage)
    {
        StringBuilder Html = new StringBuilder();
        try
        {
            if (!string.IsNullOrEmpty(strlistotherimage))
            {
                //hdItemOtherImages.Value = value_hidden;
                string[] arrListImage = strlistotherimage.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                List<string> myList = new List<string>(arrListImage);
                for (int i = 0; i < myList.Count; i++)
                {
                    if (myList[i].ToLower().Equals(imagename.ToLower()))
                    {
                        myList.RemoveAt(i);
                    }
                }
                //List<ClsImage> myListImage = new List<ClsImage>();
                //for (int i = 0; i < arrListImage.Length; i++)
                //{
                //    ClsImage item=new ClsImage();
                //    item.ImageName=arrListImage[i];
                //    myListImage.Add(item);
                //}
                string[] LaststrListOtherImage = (string[])myList.ToArray();
                if (LaststrListOtherImage.Length > 0)
                {
                    strlistotherimage = "";
                    for (int i = 0; i < LaststrListOtherImage.Length; i++)
                    {
                        if (i == 0)
                            strlistotherimage += LaststrListOtherImage[i];
                        else
                            strlistotherimage += ";" + LaststrListOtherImage[i];
                    }
                }
                else
                {
                    strlistotherimage = "";
                }
                lstOtherImage = strlistotherimage;
                Html.Append(
                "<div class=\"divhidden\">\n" +
                "    <input id=\"strListOtherImage\" type=\"hidden\" value=\"" + lstOtherImage + "\" />\n" +
                "</div>\n" +
                "<table style=\"width: 200px;\" cellpadding=\"0px\" cellspacing=\"0px\">\n" +
                "	<tr>\n" +
                "		<td>\n" +
                "			Hiển thị ảnh liên quan \n" +
                "		</td>\n" +
                "		<td style=\"text-align:center; width:40px\">\n" +
                "		</td>\n" +
                "	</tr>\n");
                string[] arrListImageLast = strlistotherimage.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (arrListImageLast.Length > 0)
                {
                    for (int i = 0; i < arrListImageLast.Length; i++)
                    {
                        Html.Append(
                    "	<tr>\n" +
                    "		<td>\n" +
                    "           <a rel=\"lightbox-journey\" title=\"" + arrListImage[i] + "\"  href=\"../images/" + arrListImageLast[i] + "\">\n" +
                    "	            <img  style=\"height:40px;\" src=\"../smallimages/" + arrListImageLast[i] + "\" />\n" +
                    "           </a>\n" +                    
                    "		</td>\n" +
                    "		<td style=\"text-align:center; height:50px\">\n" +
                    "			<a href=\"javascript:DeleteImageFromList('" + arrListImageLast[i] + "');\" title=\"Xóa\"><img src=\"../images/icons/icon_delete.jpg\" border=\"0px\"/></a> \n" +
                    "		</td>\n" +
                    "	</tr>\n");
                    }
                }
                Html.Append(
                "</table>\n"
                );
            }
        }
        catch (Exception ex)
        {
            Html.Append("ERROR: " + ex.Message.ToString());
        }
        return Html.ToString();  
        //divContentListImage.InnerHtml = Html.ToString();
    }   
}